#!/bin/sh

set -e
set -u

# Get $XKBMODEL, $XKBLAYOUT, $XKBVARIANT and $XKBOPTIONS
. /var/lib/tails-user-session/keyboard

if [ -z "${XKBVARIANT:-}" ] ; then
	XKBCONF="$XKBLAYOUT"
else
	XKBCONF="$XKBLAYOUT+$XKBVARIANT"
fi

# Choose the keyboard layout we'll use regardless of the IBus input methods
if [ "$XKBLAYOUT" = 'us' ] ; then
    SOURCES="('xkb', '$XKBCONF')"
else
    SOURCES="('xkb', '$XKBCONF'), ('xkb', 'us')"
fi

# Choose preferred IBus input methods
LANGPREFIX=`echo "$LANG" | sed 's/_.*//'`
case "$LANGPREFIX" in
   ja)
      PRELOAD="['anthy', 'pinyin', 'hangul', 'Unikey', 'bopomofo']"
      SOURCES="[$SOURCES, ('ibus', 'anthy'), ('ibus', 'pinyin'), ('ibus', 'hangul'), ('ibus', 'Unikey'), ('ibus', 'bopomofo')]"
      NEEDIBUS='y'
      ;;
   ko)
      PRELOAD="['hangul', 'pinyin', 'anthy', 'Unikey', 'bopomofo']"
      SOURCES="[$SOURCES, ('ibus', 'hangul'), ('ibus', 'pinyin'), ('ibus', 'anthy'), ('ibus', 'Unikey'), ('ibus', 'bopomofo')]"
      NEEDIBUS='y'
      ;;
   vi)
      PRELOAD="['Unikey', 'hangul', 'pinyin', 'anthy', 'bopomofo']"
      SOURCES="[$SOURCES, ('ibus', 'Unikey'), ('ibus', 'hangul'), ('ibus', 'pinyin'), ('ibus', 'anthy'), ('ibus', 'bopomofo')]"
      NEEDIBUS='y'
      ;;
   zh)
      PRELOAD="['pinyin', 'bopomofo', 'anthy', 'hangul', 'Unikey']"
      SOURCES="[$SOURCES, ('ibus', 'pinyin'), ('ibus', 'bopomofo'), ('ibus', 'anthy'), ('ibus', 'hangul'), ('ibus', 'Unikey')]"
      NEEDIBUS='y'
      ;;
   *)
      PRELOAD="['pinyin', 'anthy', 'hangul', 'Unikey', 'bopomofo']"
      SOURCES="[$SOURCES, ('ibus', 'pinyin'), ('ibus', 'anthy'), ('ibus', 'hangul'), ('ibus', 'Unikey'), ('ibus', 'bopomofo')]"
      NEEDIBUS='n'
      ;;
esac

# Configure enabled input methods and their preferred order
dconf write /desktop/ibus/general/preload-engines "$PRELOAD"
dconf write /org/gnome/desktop/input-sources/sources "$SOURCES"
if [ -n "${XKBOPTIONS:-}" ] ; then
    dconf write /org/gnome/desktop/input-sources/xkb-options "$XKBOPTIONS"
fi

# Export environment variables to enable use of IBus
export GTK_IM_MODULE='ibus'
export QT_IM_MODULE='ibus'
export XMODIFIERS='@im=ibus'
